const { app, BrowserWindow ,session } = require('electron');
const { exec } = require('child_process');
const path = require('path');

app.on('will-quit', () => {
  // 清除缓存
  session.defaultSession.clearCache().then(() => {
    console.log('Cache cleared successfully on quit');
  }).catch(error => {
    console.error('Failed to clear cache:', error);
  });

  // 清除本地存储数据
  session.defaultSession.clearStorageData().then(() => {
    console.log('Storage data cleared successfully on quit');
  }).catch(error => {
    console.error('Failed to clear storage data:', error);
  });
});

const createWindow = (file) => {
  const win = new BrowserWindow({
    width: 1000,
    height: 600,
    autoHideMenuBar: true,
    icon:path.join(__dirname, 'icon.ico'),
  });
  win.loadFile(file);
};

const pingURL = 'cdsygz.s3.bitiful.net';

exec(`ping -w 5 ${pingURL}`, (error, stdout, stderr) => {
  if (error) {
    console.error(`ping failed: ${error.message}`);
    if (!app.isReady()) {
      app.whenReady().then(() => createWindow('404.html'));
    } else {
      createWindow('404.html');
    }
  } else {
    console.log('ping succeeded');
    if (!app.isReady()) {
      app.whenReady().then(() => createWindow('index.html'));
    } else {
      createWindow('index.html');
    }
  }
});

app.whenReady().then(() => {
  // createWindow() 的调用移到了ping操作的结果处理中

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      // 此处我们假设如果应用被激活且没有窗口时，应尝试ping并加载index.html
      // 如果您希望在无法ping通时重新创建404窗口，则需要调整逻辑
      createWindow('index.html');
    }
  })
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
